<template>
  <div class="banner">
    <Row class="margin-top-10">
      <p class="find" style="margin-bottom: 20px;">
        <b class="banner__title">首页轮播图管理</b>
        <i-input
          class="banner__input"
          v-model="searchStr"
          placeholder="试试搜索轮播图描述"
          clearable
        ></i-input>
        <Button type="primary" @click="findData">查询</Button>
        <Button class="right" type="success" @click="handleAdd">新增</Button>
      </p>
      <Table :columns="columns" :data="datas" :loading="loading"></Table>
      <Page
        class="pager"
        v-if="total > 0"
        :total="total"
        show-total
        show-elevator
        show-sizer
        :page-size="limit"
        @on-change="handlePageChange"
        @on-page-size-change="handlePageSizeChange"
      />
      <!-- 新增修改弹窗 -->
      <Modal
        class="common-dialog"
        v-model="showModal"
        :title="modalTitle"
        :loading="modalLoading"
        width="600"
        :mask-closable="false"
      >
        <Form ref="modalForm" :model="modalData" :rules="modalRule" :label-width="100">
          <FormItem prop="img_url" label="图片地址" :error="modalError.img_url">
            <m-uploader
              :value.sync="modalData.img_url"
              :max-size="200 * 1024"
              desc="请上传347x175尺寸大小的图片，否则图片会自动放大来适配当前大小"
            />
          </FormItem>
          <FormItem prop="background" label="背景颜色" :error="modalError.background">
            <ColorPicker v-model="modalData.background" />
            <p style="color: #999">&nbsp;&nbsp;背景色用来衬托轮播图，请务必设置相匹配的颜色</p>
          </FormItem>
          <FormItem prop="url" label="跳转地址" :error="modalError.type">
            <m-address-input :value.sync="modalData.url" :params.sync="modalData.url_params" />
          </FormItem>
          <FormItem prop="des" label="描述" :error="modalError.des">
            <Input
              v-model="modalData.des"
              type="textarea"
              :autosize="{ minRows: 4,maxRows: 6 }"
              placeholder="输入图片描述，将会展示在图片下方"
              style="font-size: 12px"
            />
          </FormItem>
          <FormItem prop="show" label="是否展示" :error="modalError.show">
            <i-switch v-model="modalData.show" />
          </FormItem>
        </Form>
        <div slot="footer">
          <Button type="text" @click="handleModalCancel">取消</Button>
          <Button type="primary" @click="handleModalConfrim">确认</Button>
        </div>
      </Modal>
    </Row>
  </div>
</template>

<script>
import http from '@/utils/http';
import moment from 'moment';
// NO-COMMON
import Uploader from '@/components/uploader';
import ImagePreview from '@/components/uploader/components/ImagePreview';
import AddressInput from '@/components/address-input';
// 默认数据
const DEFAULT_DATA = {
  img_url: '',
  background: '',
  url: '',
  url_params: {},
  des: '',
  show: true
};
// 模块名称
const NAME = '轮播图';
const MODULE = 'banner';
const RULE = {
  img_url: [{ required: true, message: '请上传图片', trigger: 'change' }],
  background: [{ required: true, message: '请选择背景色', trigger: 'select' }],
  url: [{ required: true, message: '请填写跳转地址', trigger: 'change' }],
  des: [{ required: true, message: '请输入轮播图的描述', trigger: 'input' }]
};

export default {
  name: MODULE,

  components: {
    [Uploader.name]: Uploader,
    [AddressInput.name]: AddressInput
  },

  data () {
    return {
      loading: true,
      searchStr: '',
      datas: [],
      total: 0,
      page: 1,
      limit: 10,
      columns: [
        {
          title: '序号',
          key: 'index',
          width: 80,
          align: 'center'
        },
        {
          title: '图片',
          align: 'center',
          width: 240,
          render: (h, params) => {
            return <ImagePreview src={params.row.img_url} width="200px" height="80px" style="margin: 6px  auto" has-remove={false} />;
          }
        },
        {
          title: '背景色',
          align: 'center',
          render: (h, params) => {
            return <div style={{ width: '20px', height: '20px', margin: '0 auto', background: params.row.background }} />;
          }
        },
        {
          title: '跳转类型',
          align: 'center',
          key: 'type',
          render: (h, params) => {
            const { jumpType } = params.row.url_params;
            if (+jumpType === 1) {
              return <Tag color="#888888">书城页面</Tag>;
            } else if (+jumpType === 2) {
              return <Tag color="#cccccc">其他链接</Tag>;
            } else {
              return <Tag>未知类型</Tag>;
            }
          }
        },
        {
          title: '跳转地址',
          align: 'center',
          render: (h, params) => {
            return h('span', params.row.url);
          }
        },
        {
          title: '描述信息',
          align: 'center',
          key: 'des',
          render: (h, params) => {
            return <span class="two-row-ellipsis">{params.row.des}</span>;
          }
        },
        {
          title: '是否展示',
          align: 'center',
          key: 'show',
          width: 90,
          render: (h, params) => {
            return <i-switch size="small" value={params.row.show} disabled />;
          }
        },
        {
          title: '创建时间',
          align: 'center',
          key: 'create_time',
          render: (h, params) => {
            return (
              <span>
                {moment(params.row.create_time).format('YYYY/MM/DD HH:MM:SS')}
              </span>
            );
          }
        },
        {
          title: '操作',
          align: 'center',
          width: 200,
          key: 'handle',
          render: (h, params) => {
            return (
              <div>
                <Button
                  type="primary"
                  size="small"
                  class="text-red"
                  onClick={() => this.handleTop(params.row)}
                >
                  置顶
                </Button>
                <Button
                  type="primary"
                  size="small"
                  class="text-red"
                  onClick={() => this.handleUpdate(params.row)}
                >
                  修改
                </Button>
                <Button
                  type="error"
                  size="small"
                  class="text-red"
                  onClick={() => this.handleDelete(params.row)}
                >
                  删除
                </Button>
              </div>
            );
          }
        }
      ],
      showModal: false, // 控制modal的显隐
      modalLoading: false, // 点击modal确定按钮是否显示loading
      modalTitle: '', // modal标题
      isAddOrUpdate: '', // 是新增弹窗或者更新弹窗
      currentId: '', // 当前正在修改的商品Id
      modalData: { ...DEFAULT_DATA },
      modalRule: RULE,
      modalError: {}
    };
  },
  methods: {
    // 获取数据
    getData () {
      this.loading = true;
      http({
        method: 'GET',
        url: `/api/admin/${MODULE}`,
        params: {
          page: this.page,
          limit: this.limit,
          search: this.searchStr
        },
        operation: `获取${NAME}`
      }).then(res => {
        this.loading = false;
        if (res.data && res.ok) {
          this.datas = res.data.list.map((item, index) => {
            item.index = (this.page - 1) * this.limit + index + 1;
            return item;
          });
          this.total = res.data.total;
        }
      });
    },
    // 查找数据
    findData () {
      this.limit = 10;
      this.page = 1;
      this.total = 0;
      this.getData();
    },
    // 打开新增弹窗
    handleAdd () {
      this.modalData = { ...DEFAULT_DATA };
      this.showModal = true;
      this.modalTitle = `新增${NAME}`;
      this.isAddOrUpdate = 'add';
    },
    // 置顶数据
    handleTop (item) {
      http({
        method: 'POST',
        url: `/api/admin/${MODULE}/exchange`,
        data: {
          id: item._id,
          from: item.priority,
          to: 1
        },
        operation: `置顶${NAME}`
      }).then(res => {
        if (res.data && res.ok) {
          this.$Message.success(`置顶${NAME}成功`);
          this.getData();
        }
      });
    },
    // 打开修改弹窗
    handleUpdate (item) {
      Object.keys(DEFAULT_DATA).forEach(key => {
        this.modalData[key] = item[key];
      });
      this.showModal = true;
      this.modalTitle = `修改${NAME}`;
      this.isAddOrUpdate = 'update';
      this.currentId = item._id;
    },
    // 删除数据
    handleDelete (item) {
      this.$Modal.confirm({
        title: '温馨提示',
        content: `确定要删除此${NAME}？`,
        onOk: () => {
          http({
            method: 'DELETE',
            url: `/api/admin/${MODULE}/${item._id}`,
            operation: `删除${NAME}`
          }).then(res => {
            if (res.data && res.ok) {
              // 更新datas
              this.showModal = false;
              this.$Message.success(`删除${NAME}成功`);
              this.getData();
            }
          });
        },
        onCancel: () => {}
      });
    },
    // 自定义校验
    selfValidator (data) {
      return true;
    },
    // 取消弹窗loading
    closeModalLoading () {
      this.modalLoading = false;
      // 避免校验完直接关闭弹窗
      this.$nextTick(() => {
        this.modalLoading = true;
        this.showModal = true;
      });
    },
    handleModalConfrim () {
      // 合法性校验
      this.$refs['modalForm'].validate(valid => {
        if (valid) {
          // 如果全部校验通过，发送POST请求
          if (this.selfValidator(this.modalData)) {
            if (this.isAddOrUpdate === 'add') {
              this.modalLoading = true;
              http({
                method: 'POST',
                url: `/api/admin/${MODULE}`,
                data: this.modalData,
                operation: `新增${NAME}`
              })
                .then(res => {
                  this.modalLoading = false;
                  if (res.data && res.ok) {
                    this.showModal = false;
                    this.$Message.success(`新增${NAME}成功`);
                    this.getData();
                  }
                })
                .catch(err => {
                  this.modalLoading = false;
                  this.$Message.error(`新增${NAME}失败, ${err.toString}`);
                });
            } else if (this.isAddOrUpdate === 'update') {
              this.modalLoading = true;
              http({
                method: 'PUT',
                url: `/api/admin/${MODULE}/${this.currentId}`,
                data: this.modalData,
                operation: `修改${NAME}`
              })
                .then(res => {
                  this.modalLoading = false;
                  if (res.data && res.ok) {
                    this.showModal = false;
                    this.$Message.success(`修改${NAME}成功`);
                    this.getData();
                  }
                })
                .catch(err => {
                  this.modalLoading = false;
                  this.$Message.error(`新增${NAME}失败, ${err.toString}`);
                });
            }
          }
        }
      });
    },
    handleModalCancel () {
      this.$refs['modalForm'].resetFields();
      this.showModal = false;
    },
    // 点击分页
    handlePageChange (val) {
      this.page = val;
      this.getData();
    },
    handlePageSizeChange (size) {
      this.limit = size;
      this.getData();
    }
  },
  created () {
    this.getData();
  }
};
</script>

<style lang="scss">
.banner {
  &__title {
    font-size: 16px;
  }

  &__input {
    display: inline-block;
    width: 200px;
    margin-left: 20px;
    margin-right: 20px
  }

  .right {
    float: right;
  }
  .add-icon {
    float: right;
  }
  .overflow-text {
    width: 100%;
    overflow: hidden;
    text-overflow: ellipsis;
  }
  .ivu-tooltip-inner {
    max-width: inherit;
  }
  .change-btn {
    margin-right: 15px;
  }
  .pager {
    text-align: right;
    margin-top: 30px;
  }
}

.common-dialog textarea.ivu-i-input {
  font-size: 12px !important;
}
</style>
